package cjj;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/admin/publishMovie")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2,
        maxFileSize = 1024 * 1024 * 10,
        maxRequestSize = 1024 * 1024 * 50)
public class AdminPublishMovieServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 验证管理员身份
        Integer adminId = (Integer) request.getSession().getAttribute("adminId");
        if (adminId == null) {
            response.sendRedirect("/admin/login");
            return;
        }

        // 获取表单参数
        String title = request.getParameter("title");
        String director = request.getParameter("director");
        String releaseDate = request.getParameter("releaseDate");
        String actors = request.getParameter("actors");
        String genre = request.getParameter("genre");
        String country = request.getParameter("country");
        String language = request.getParameter("language");
        String durationStr = request.getParameter("duration");
        String description = request.getParameter("description");
        Part coverImagePart = request.getPart("coverImage");

        // 数据验证
        if (title == null || title.isEmpty() || director == null || director.isEmpty() ||
                releaseDate == null || releaseDate.isEmpty() || actors == null || actors.isEmpty() ||
                genre == null || genre.isEmpty() || country == null || country.isEmpty() ||
                language == null || language.isEmpty() || durationStr == null || durationStr.isEmpty() ||
                description == null || description.isEmpty() || coverImagePart == null || coverImagePart.getSize() <= 0) {

            request.getSession().setAttribute("errorMessage", "所有带*的字段和封面图片必须填写/上传");
            response.sendRedirect(request.getContextPath() + "/cjj/publish_movie.jsp");
            return;
        }

        try {
            int duration = Integer.parseInt(durationStr);
            if (duration < 1) {
                request.getSession().setAttribute("errorMessage", "片长必须大于0分钟");
                response.sendRedirect(request.getContextPath() + "/cjj/publish_movie.jsp");
                return;
            }

            // 处理封面图片上传
            String coverImagePath = null;
            try {
                String fileName = extractFileName(coverImagePart);
                String uniqueFileName = generateUniqueFileName(fileName);

                String uploadPath = getServletContext().getRealPath("/") + "uploads" + File.separator + "movies";
                File uploadDir = new File(uploadPath);
                if (!uploadDir.exists()) {
                    uploadDir.mkdirs();
                }

                String savePath = uploadPath + File.separator + uniqueFileName;
                coverImagePart.write(savePath);
                coverImagePath = "uploads/movies/" + uniqueFileName;
            } catch (Exception e) {
                request.getSession().setAttribute("errorMessage", "封面图片上传失败: " + e.getMessage());
                response.sendRedirect(request.getContextPath() + "/cjj/publish_movie.jsp");
                return;
            }

            // 数据库操作
            try (Connection conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/webproject_2025?useUnicode=true&characterEncoding=UTF-8",
                    "root", "root")) {

                String sql = "INSERT INTO movie (TITLE, DIRECTOR, RELEASE_DATE, ACTORS, GENRE, COUNTRY, LANGUAGE, DURATION, DESCRIPTION, COVER_IMAGE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

                try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                    stmt.setString(1, title);
                    stmt.setString(2, director);
                    stmt.setString(3, releaseDate);
                    stmt.setString(4, actors);
                    stmt.setString(5, genre);
                    stmt.setString(6, country);
                    stmt.setString(7, language);
                    stmt.setInt(8, Integer.parseInt(durationStr));
                    stmt.setString(9, description);
                    stmt.setString(10, coverImagePath);

                    int rows = stmt.executeUpdate();
                    if (rows > 0) {
                        request.getSession().setAttribute("successMessage", "电影发布成功");
                    } else {
                        request.getSession().setAttribute("errorMessage", "电影发布失败，请重试");
                    }
                }
            }
        } catch (NumberFormatException e) {
            request.getSession().setAttribute("errorMessage", "片长必须为数字");
        } catch (SQLException e) {
            e.printStackTrace();
            request.getSession().setAttribute("errorMessage", "数据库错误: " + e.getMessage());
        } finally {
            response.sendRedirect(request.getContextPath() + "/cjj/publish_movie.jsp");
        }
    }

    private String extractFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] items = contentDisp.split(";");
        for (String item : items) {
            if (item.trim().startsWith("filename")) {
                return item.substring(item.indexOf("=") + 2, item.length() - 1);
            }
        }
        return "";
    }

    private String generateUniqueFileName(String originalFileName) {
        String timestamp = dateFormat.format(new Date());
        String extension = "";
        int dotIndex = originalFileName.lastIndexOf('.');
        if (dotIndex > 0) {
            extension = originalFileName.substring(dotIndex);
        }
        return timestamp + "_" + System.currentTimeMillis() + extension;
    }
}